package com.mjfeed.controller.admin;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mjfeed.ExcelView;
import com.mjfeed.controller.BaseController;
import com.mjfeed.dto.OrderDto;
import com.mjfeed.entity.Admin;
import com.mjfeed.entity.Area;
import com.mjfeed.entity.DeliveryCorp;
import com.mjfeed.entity.Order;
import com.mjfeed.entity.OrderItem;
import com.mjfeed.entity.Shipping;
import com.mjfeed.entity.ShippingItem;
import com.mjfeed.service.AdminService;
import com.mjfeed.service.AreaService;
import com.mjfeed.service.DeliveryCorpService;
import com.mjfeed.service.OrderService;
import com.mjfeed.util.Format;
import com.mjfeed.util.Pagination;
import com.mjfeed.util.ParamBean;

/**
 * @description 订单
 * @author zhaominglei
 * @date 2014年10月4日
 */
@Controller("adminOrderController")
@RequestMapping("/admin/order")
public class OrderController extends BaseController{
	@Resource(name="orderService")
	private OrderService orderService;
	@Resource(name="adminService")
	private AdminService adminService;
	@Resource(name="areaService")
	private AreaService areaService;
	@Resource(name = "deliveryCorpService")
	private DeliveryCorpService deliveryCorpService;
	
	@RequestMapping(value = "/list" ,method=RequestMethod.GET)
	public String list(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response, Model model){
		paramBean.setUrl(getBasePath(request) + "admin/order/list.shtml");
		int p = (Format.null2Zero(request.getParameter("p")) == 0) ? 1 : Format.null2Zero(request.getParameter("p"));
		paramBean.setPage(p);
		Pagination<Order> pagination = orderService.getPagination(paramBean);
		request.setAttribute("pagination", pagination);
		return "admin/order/list";
	}
	
	@RequestMapping(value = "/export" ,method=RequestMethod.GET)
	public ModelAndView export(ParamBean paramBean, HttpServletRequest request, HttpServletResponse response, ModelMap model){
		paramBean.setUrl(getBasePath(request) + "admin/order/list.shtml");
		paramBean.setPage(0);
		paramBean.setPageSize(0);
		Pagination<Order> pagination = orderService.getPagination(paramBean);
		List<Order> datas = pagination.getRecordList();
		List<OrderDto> dtos=new ArrayList<OrderDto>();
		entiy2Dto(datas,dtos);
		String filename = "orderlist_" + new SimpleDateFormat("yyyyMM").format(new Date()) + ".xls";
		return new ModelAndView(new ExcelView(filename, null, 
				new String[] { "sn","amount","username","consignee","paymentMethodName","shippingMethodName","orderStatus","paymentStatus","shippingStatus","createDate"}, 
				new String[] { "订单编号","订单金额","会员","收货人","支付方式名称","配送方式名称","订单状态","支付状态","配送状态","创建日期"}, 
				new Integer[]{4000,4000,4000,4000,6000,6000,6000,6000,6000,6000}
				, null, dtos, null), model);
	}

	private void entiy2Dto(List<Order> datas, List<OrderDto> dtos) {
		for(Order data:datas){
			OrderDto dto=new OrderDto();
			dto.setSn(data.getSn());
			dto.setAmount(data.getAmount().toString());
			dto.setUsername(data.getMember().getUsername());
			dto.setConsignee(data.getConsignee());
			dto.setPaymentMethodName(data.getPaymentMethodName());
			dto.setShippingMethodName(data.getShippingMethodName());
			dto.setOrderStatus(data.getOrderStatusLabel());
			if(data.isExpired()){
				dto.setOrderStatus(dto.getOrderStatus()+"(已过期)");
			}
			dto.setPaymentStatus(data.getPaymentStatusLabel());
			dto.setShippingStatus(data.getShippingStatusLabel());
			dto.setCreateDate(data.getCreateDate());
			dtos.add(dto);
		}
	}
	
	@RequestMapping(value = "/edit" ,method=RequestMethod.GET)
	public String edit(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("order", orderService.getById(Order.class, id));
		return "admin/order/edit";
	}
	
	@RequestMapping(value = "/update" ,method=RequestMethod.POST)
	public String update(Order order, HttpServletRequest request, HttpServletResponse response, Model model){
		Order pOrder = orderService.getById(Order.class, order.getId());
		if (pOrder == null) {
			return ERROR_VIEW;
		}
		if (pOrder.isExpired() || pOrder.getOrderStatus() != 0) {
			return ERROR_VIEW;
		}
		Admin admin = adminService.getCurrent();
		if (pOrder.isLocked(admin)) {
			return ERROR_VIEW;
		}
		pOrder.setIsInvoice((order.getIsInvoice() != null && order.getIsInvoice()) ? true : false);
		pOrder.setInvoiceTitle(order.getInvoiceTitle());
		pOrder.setConsignee(order.getConsignee());
		pOrder.setArea(areaService.getById(Area.class, Long.valueOf(request.getParameter("areaId"))));
		pOrder.setAddress(order.getAddress());
		pOrder.setZipCode(order.getZipCode());
		pOrder.setPhone(order.getPhone());
		pOrder.setOperator(admin);
		orderService.update(pOrder);
		return "redirect:/admin/order/list.shtml";
	}
	
	@RequestMapping(value = "/view" ,method=RequestMethod.GET)
	public String view(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("order", orderService.getById(Order.class, id));
		return "admin/order/view";
	}
	
	@RequestMapping(value = "/stockout" ,method=RequestMethod.GET)
	public String stockout(Long id, HttpServletRequest request, HttpServletResponse response, Model model){
		request.setAttribute("order", orderService.getById(Order.class, id));
		request.setAttribute("deliveryCorps", deliveryCorpService.getAll(DeliveryCorp.class));
		return "admin/order/stockout";
	}
	
	@RequestMapping(value = "/shipping" ,method=RequestMethod.POST)
	public String shipping(Long id, Long deliveryCorpId, HttpServletRequest request, HttpServletResponse response, Model model){
		if (id == null) {
			return ERROR_VIEW;
		}
		Order pOrder = orderService.getById(Order.class, id);
		if (pOrder == null) {
			return ERROR_VIEW;
		}
		if (pOrder.isExpired() || pOrder.getOrderStatus() != 1) {
			return ERROR_VIEW;
		}
		if (pOrder.getShippingStatus() != 0 && pOrder.getShippingStatus() != 1) {
			return ERROR_VIEW;
		}
		DeliveryCorp deliveryCorp = deliveryCorpService.getById(DeliveryCorp.class, deliveryCorpId);
		if (deliveryCorp == null) {
			return ERROR_VIEW;
		}
		Admin admin = adminService.getCurrent();
		if (pOrder.isLocked(admin)) {
			return ERROR_VIEW;
		}
		Shipping shipping = new Shipping();
		shipping.setAddress(pOrder.getAddress());
		shipping.setArea(pOrder.getAreaName());
		shipping.setConsignee(pOrder.getConsignee());
		shipping.setDeliveryCorp(deliveryCorp);
		shipping.setPhone(pOrder.getPhone());
		shipping.setShippingMethod(pOrder.getShippingMethodName());
		shipping.setSn(pOrder.getSn());
		shipping.setTrackingNo(request.getParameter("trackingNo"));
		shipping.setZipCode(pOrder.getZipCode());
		shipping.setOrder(pOrder);
		shipping.setOperator(admin);
		List<ShippingItem> shippingItems = new ArrayList<ShippingItem>();
		for (OrderItem orderItem : pOrder.getOrderItems()) {
			ShippingItem shippingItem = new ShippingItem();
			shippingItem.setName(orderItem.getName());
			shippingItem.setQuantity(orderItem.getQuantity());
			shippingItem.setSn(orderItem.getProduct().getSn());
			shippingItem.setProduct(orderItem.getProduct());
			shippingItem.setShipping(shipping);
			shippingItems.add(shippingItem);
		}
		shipping.setShippingItems(shippingItems);
		orderService.shipping(pOrder, shipping, admin);
		return "redirect:/admin/order/list.shtml";
	}
}
